﻿/****************************************************************************
**
** Copyright (C) 2017 The Qt Company Ltd.
** Contact: https://www.qt.io/licensing/
**
** This file is part of the examples of the Qt Toolkit.
**
** $QT_BEGIN_LICENSE:BSD$
** Commercial License Usage
** Licensees holding valid commercial Qt licenses may use this file in
** accordance with the commercial license agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and The Qt Company. For licensing terms
** and conditions see https://www.qt.io/terms-conditions. For further
** information use the contact form at https://www.qt.io/contact-us.
**
** BSD License Usage
** Alternatively, you may use this file under the terms of the BSD license
** as follows:
**
** "Redistribution and use in source and binary forms, with or without
** modification, are permitted provided that the following conditions are
** met:
**   * Redistributions of source code must retain the above copyright
**     notice, this list of conditions and the following disclaimer.
**   * Redistributions in binary form must reproduce the above copyright
**     notice, this list of conditions and the following disclaimer in
**     the documentation and/or other materials provided with the
**     distribution.
**   * Neither the name of The Qt Company Ltd nor the names of its
**     contributors may be used to endorse or promote products derived
**     from this software without specific prior written permission.
**
**
** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
** "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
** LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
** A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
** OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
** SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
** LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
** DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
** THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
** (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
** OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE."
**
** $QT_END_LICENSE$
**
****************************************************************************/

import QtQuick 2.12
import QtQuick.Layouts 1.12
import QtQuick.Controls 2.12
import QtQuick.Controls.Material 2.0
import QtGraphicalEffects 1.0
import QtQuick.Window 2.2
import "qrc:/MaterialUI/"
import "qrc:/MaterialUI/Interface/"
import "ItemSentance/"
Page {
    id: root

    property string inConversationWith
    property string inConversationMail
    property string nowmessageField

    function updateNowmessage(value){
        nowmessageField = value
        messageField.text = value
        qrCode.hide()
    }

    Component.onCompleted: {
        messageField.forceActiveFocus()
    }

    FileImageView{
        id:imageView
        visible: false
    }
    CustomQrCode{
        id:qrCode
        z:2
        anchors.fill: listView
        itemWidth: 200
        itemHeight: 200
    }

    ListView {
        id: listView
        anchors.left: parent.left
        anchors.right: parent.right
        anchors.top: parent.top
        anchors.bottom: pane.top
        displayMarginBeginning: 40
        displayMarginEnd: 40
        verticalLayoutDirection: ListView.BottomToTop
        spacing: 12
        model:SqlConversationModel
        clip: true
        delegate: Column {
            anchors.right: sentByMe ? listView.contentItem.right : undefined
            spacing: 6

            readonly property bool sentByMe: model.recipient!=="GROUP"?model.recipient !== SqlConversationModel.me:model.author===ChatManage.MyInfo["user_mail"]
            readonly property bool isImage: model.type==="1"?false:isAssetTypeAnImage(model.message.slice(0,model.message.indexOf("|")))
            readonly property string formate:typeFormate(model.message.slice(0,model.message.indexOf("|")))

            function isAssetTypeAnImage(filePath) {
                var index= filePath.lastIndexOf(".");
                var ext = filePath.substr(index+1);
                return [
                            'png', 'jpg', 'jpeg', 'bmp', 'gif', 'webp', 'psd', 'svg', 'tiff'].
                indexOf(ext.toLowerCase()) !== -1;
            }

            function typeFormate(filePath){
                var index= filePath.lastIndexOf(".");
                var ext = filePath.substr(index+1);
                return ext.toLowerCase();
            }

            MaterialLabel {
                id: timestampText
                text: model.recipient!=="GROUP"?Qt.formatDateTime(model.timestamp, "yyyy-MM-dd hh:mm"):sentByMe?Qt.formatDateTime(model.timestamp, "yyyy-MM-dd hh:mm"):SqlContactModel.getMailName(model.author)+Qt.formatDateTime(model.timestamp, "  yyyy-MM-dd hh:mm")
                color: "lightgrey"
                anchors.right: sentByMe ? parent.right : undefined
                anchors.rightMargin: sentByMe ? 65 : undefined
                anchors.left: sentByMe ? undefined : parent.left
                anchors.leftMargin: sentByMe ? undefined : 45
            }
            Grid {
                id: messageRow
                spacing: 6
                anchors.right: sentByMe ? parent.right : undefined
                anchors.rightMargin: sentByMe ? 20 : undefined
                layoutDirection:sentByMe ?Qt.RightToLeft:Qt.LeftToRight
                Image {
                    id: avatar
                    width: 40
                    height: width+10
                    verticalAlignment: Image.AlignTop
                    fillMode:Image.PreserveAspectFit
                    source: model.recipient!=="GROUP"?(!sentByMe) ? "qrc:/"+SqlContactModel.getMailImg(model.author)+".png":"qrc:/"+ChatManage.MyInfo["user_img"]+".png":(!sentByMe)?"qrc:/"+SqlContactModel.getMailImg(model.author)+".png":"qrc:/"+ChatManage.MyInfo["user_img"]+".png"
                    layer.enabled: true
                    layer.effect:DropShadow {
                        anchors.fill: avatar
                        source: avatar
                        horizontalOffset: 0
                        verticalOffset: 0
                        radius: 4
                        samples: 9
                        color: "#000000"
                        spread:0
                    }
                }

                Loader{
                    id:itemLoader
                    source:model.type==="1"?"ItemSentance/NormalSentance.qml":"ItemSentance/FileSentanceMain.qml"
                }
                Image{
                    id:tip
                    width: model.answer.slice(0,1)==="0"?25:20
                    height: 80
                    visible: model.type==="1"?false:isImage?false:true
                    fillMode:Image.PreserveAspectFit
                    source: model.answer.slice(0,1)==="0"?"qrc:/tick.png":"qrc:/cross.png"
                    layer.enabled: true
                    layer.effect:DropShadow {
                        anchors.fill: tip
                        source: tip
                        horizontalOffset: 0
                        verticalOffset: 0
                        radius: 4
                        samples: 9
                        color: "#000000"
                        spread:0
                    }
                }
            }
        }

        ScrollBar.vertical: ScrollBar {}
        Component.onCompleted: {
            listView.model = SqlConversationModel

        }
    }

    MouseArea{
        id:conversionSplit
        anchors{
            left:pane.left
            leftMargin: 10
            right:pane.right
            rightMargin: 10
            bottom: pane.top
            bottomMargin: -4
            top:pane.top
            topMargin: -4
        }
        cursorShape:Qt.SizeVerCursor
        property point startPoint: Qt.point(0,0)
        onPressed: {
            startPoint = Qt.point(mouseX,mouseY)
        }
        onPositionChanged: {
            if(pressed){
                var offsetY = mouseY-startPoint.y
                if((pane.height-offsetY>root.height/4)&&(pane.height-offsetY<root.height/4*3)){

                    pane.height -= offsetY
                }
            }
            mouse.accepted = false
        }
    }
    Rectangle {
        id: pane
        anchors{
            left: parent.left
            right: parent.right
            bottom: parent.bottom
        }
        height: parent.height/4

        color: "#F5F5F5"
        opacity:0.8

        RectangularGlow {
            z: -1
            anchors.fill: pane
            glowRadius: 6
            spread: 0.22
            color: "#20000000"
        }
        ScrollView {
            anchors{
                left: parent.left
                top: parent.top
                bottom: parent.bottom
                right: sendButton.left
            }
            clip: true
            anchors.margins: 10
            TextArea {//TextField
                id: messageField
                width: pane.width-sendButton.width-60
                height: pane.height
                cursorVisible: true
                wrapMode: Label.Wrap
                selectByMouse: true
                selectByKeyboard: true
                enabled: ChatManage.Network
                textFormat:TextEdit.AutoText
                focus: true
                background: Rectangle{
                    color: "#00000000"
                }
                Action {
                    shortcut: "Ctrl+Return" //StandardKey.Copy "Ctrl+E,Ctrl+W"
                    onTriggered: {
                        sendButton.clicked()
                    }
                }
                onTextChanged: {
                    if(messageField.text.length>2000)
                        messageField.text=messageField.text.substring(0,2000)
                    nowmessageField = text
                }
            }
        }
        Button {
            id: sendButton
            highlighted: true
            text: qsTr("发 送")
            //enabled: messageField.length > 0
            Material.theme:Material.LightBlue
            Material.accent: "lightskyblue"
            anchors{
                right: parent.right
                rightMargin: 20
                top: parent.top
                topMargin: (parent.height-height)/2
            }
            height: 40
            width: 80
            onClicked: {
                if(messageField.text.length==0)
                    return
                if(!ChatManage.Network){
                    materialUI.showSnackbarMessage("网络异常，请检查网络连接！")
                    return
                }

                if(!SqlConversationAll.sendMessage(inConversationMail, messageField.text)){
                    materialUI.showSnackbarMessage("超出发送最大字符!")
                    return
                }
                messageField.text = "";
                qrCode.hide()
            }
        }

    }

    Rectangle{
        id:dropBackground
        anchors.fill: parent
        anchors.margins: 5
        visible: false
        color: "#BDBDBD"
        radius: 2
        opacity:0.5
        Image {
            source: "qrc:/plus.png"
            anchors.centerIn: parent
        }
    }

    DropArea {
        anchors.fill: parent
        anchors.margins: 10
        onEntered:{
            dropBackground.visible = true
        }
        onExited:{
            dropBackground.visible = false
        }
        onDropped: {
            if( !drop.hasUrls ) { dropBackground.visible = false;return; }
            var filePaths = [ ];
            for( var index = 0; index < drop.urls.length; ++index )
            {
                var url = drop.urls[ index ].toString();
                console.log(url)
                if ( url.indexOf( "file://" ) !== 0 ) { dropBackground.visible = false;return; }
                if ( Qt.platform.os === "windows" )
                    filePaths.push( url.substr( 8 ) );
                else
                    filePaths.push( url.substr( 7 ) );
            }
            var rv = SqlConversationAll.sendFile(inConversationMail,filePaths);
            if(rv.length!==0){
                materialUI.showSnackbarMessage(rv)
            }
            dropBackground.visible = false
            qrCode.hide()
        }
    }
}

